<template>
  <div class="fullMain">
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{ alertText }}</alert>
    </div>
    <!-- 提醒时间选择 -->
    <alarmTime
      :isShowAlarmTime.sync="isShowAlarmTime"
      :remindInfo="remindInfo"
      @getPickedReplayTime="getPickedReplayTime"
    ></alarmTime>
    <!--顶部标题 -->
    <div style="position: fixed; width: 100%">
      <x-header
        class="header"
        :left-options="{ backText: '阶段目标', showBack: true }"
      >
        <a slot="right" @click="deleteGoal">删除</a>
      </x-header>
    </div>
    <div style="height: 20px; background-color: rgb(237, 237, 237)" />
    <group class="taskWrap">
      <x-textarea
        title="阶段目标简介："
        v-model="goalContent"
        @on-blur="onBlur"
        placeholder="会自动保存"
      ></x-textarea>
      <div class="timeInfo">
        <div class="picker" @click="isShowDeadline = !isShowDeadline">
          <div>
            <i class="fa fa-clock-o"></i>
            <span>{{ deadline === "" ? "截止日期" : deadline }}</span>
          </div>
        </div>
        <div class="picker" @click="isShowAlarmTime = true">
          <div>
            <i class="fa fa-bell-o"></i>
            <span>{{ getAlarmTime() }}</span>
          </div>
        </div>
      </div>
      <span class="alertInfo">{{ alertInfo }}</span>
      <inline-calendar
        v-if="isShowDeadline"
        ref="calendar"
        class="inline-calendar-demo"
        v-model="deadline"
        @on-select-single-date="onSelect"
        :return-six-rows="false"
        disable-past
        :highlight-weekend="true"
      >
      </inline-calendar>
      <divider>任务分工</divider>
      <ul class="goalsListWrap">
        <li class="goalsList" v-for="(item, index) in placements" :key="index">
          <div>
            <i v-if="!isFinish" class="fa fa-circle-thin circle"></i>
            <i v-else class="fa fa-check-circle circle check"></i>
            <div class="jobs">
              <span
                class="jobTitle"
                :style="{
                  color: isFinish ? 'gray' : '',
                  textDecoration: isFinish ? 'line-through' : '',
                }"
                >{{ item.jobContent }}</span
              >
              <span class="jobMember" v-if="item.userList.length === 0"
                >暂未安排人员</span
              >
              <div v-else class="jobMember">
                <span
                  v-for="(item_in, index_in) in item.userList"
                  :key="index_in"
                >
                  <span v-if="item_in.detail"
                    >{{ item_in.detail.name }}&nbsp;&nbsp;</span
                  >
                  <span v-else v-for="key in item_in" :key="key"
                    >{{ key }}&nbsp;&nbsp;</span
                  >
                </span>
              </div>
            </div>
          </div>
          <div class="edit">
            <!-- <i class="fa fa-pencil-square-o" @click="editFun(item,index)"></i> -->
            <i class="fa fa-trash" @click="deleteFun(index)"></i>
          </div>
        </li>
      </ul>

      <div class="addJob">
        <div class="picker" @click="addMember">
          <div v-if="this.goalMemberChoosedItem.length === 0">
            <i class="fa fa-user-plus"></i>
            <span>负责人</span>
          </div>
          <div v-else class="choosedUser">
            <img :src="this.goalMemberChoosedItem[0].detail.avatar" />
            <span>{{ this.goalMemberChoosedItem[0].detail.name }}</span>
          </div>
        </div>

        <div class="addWrap">
          <p class="addButton" v-show="!!jobContent" @click="addJob">添加</p>
          <x-textarea
            class="jobContent"
            placeholder="请输入分工内容"
            v-model="jobContent"
            show-counter
          />
        </div>
      </div>
    </group>
  </div>
</template>

<script>
import { XHeader, Group, XTextarea, Divider, InlineCalendar } from "vux";
import task from "api/task";
import alarmTime from "components/AlarmTime/alarmTime";
import time from "utilMethods/time.js";
export default {
  components: {
    XHeader,
    Group,
    XTextarea,
    Divider,
    InlineCalendar,
    alarmTime,
  },
  data() {
    return {
      alertText: "",
      isShowAlert: false,
      goalContent:
        localStorage.getItem("goalContent") != "null"
          ? localStorage.getItem("goalContent")
          : "",
      jobContent: localStorage.getItem("jobContent"),
      memberList: [], //成员列表，传给人员展示页面
      taskItem: "",
      goalMemberChoosedItem: [], //每次分工的负责人
      placements: [], //任务的分工
      isFinish: false,
      goal: "",
      flagOfGoal: false, //true是修改，false是新增
      goalId:
        localStorage.getItem("goalId") == null
          ? ""
          : localStorage.getItem("goalId"),
      isShowDeadline: false,
      deadline: "",
      isShowAlarmTime: false,
      remindInfo: {
        remindTime: "",
        remindDays: [],
      },

      alertInfo: "",
      nowTemp: {}, //目前正在填写的分工
      isAdd: true, //true表示添加，false表示删除
      isOnBlur: false, //判断是不是只需修改阶段目标简介
    };
  },
  mounted() {
    this.getInitItem();
    this.getGoalMemberChoosedItem();
  },

  methods: {
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    getInitItem() {
      let temp = localStorage.getItem("goal");
      if (!!temp) {
        this.goal = JSON.parse(temp);
        this.flagOfGoal = true;
        this.deadline = this.goal.deadline;
        this.remindInfo = {
          remindTime: this.goal.time,
          remindDays: this.goal.weeks,
        };
        // 这个判断不对
        // this.isFinish = this.goal.status==1?true:false
      }
      // 选中的task
      this.taskItem = localStorage.getItem("taskItem");
      if (!!this.taskItem) {
        this.taskItem = JSON.parse(this.taskItem);
      }
      if (this.goalId === "" || this.goalId === undefined) {
        localStorage.setItem("placements", "");
      }
      // 该页面的goals,如果goal有值，就用goal的。否则用缓存的
      //如果是选人会来，goal没有更新，这个页面之前删除和新增操作也都没有及时更新
      //因此，再用一个goal的值”member“表示从选人页面来的，取缓存的数据，而不是上一个页面来的数据
      if (this.flagOfGoal && temp.indexOf("placements") !== -1) {
        this.goalContent = this.goal.goalContent;
        this.placements = this.goal.placements;
      } else {
        let placementsTemp = localStorage.getItem("placements");
        if (
          placementsTemp !== undefined &&
          placementsTemp !== null &&
          placementsTemp !== ""
        ) {
          this.placements = JSON.parse(placementsTemp);
        }
      }
    },
    onBlur() {
      this.isOnBlur = true;
      this.addGoal();
    },
    getGoalMemberChoosedItem() {
      this.goalMemberChoosedItem = localStorage.getItem(
        "goalMemberChoosedItem"
      );
      if (!!this.goalMemberChoosedItem) {
        this.goalMemberChoosedItem = JSON.parse(this.goalMemberChoosedItem);
      }
      localStorage.setItem("goalMemberChoosedItem", "");
    },
    addMember() {
      this.getMemberList();
      // 这里是为了区分是否从人员选择页面过来，是的话，给goal赋值goalId，判断其直接用页面的缓存
      localStorage.setItem(
        "goal",
        JSON.stringify({ goalId: this.goal.goalId })
      );
      console.log("this.remindInfo");
      console.log(this.remindInfo);
      localStorage.setItem("deadline", this.deadline);
      localStorage.setItem("remindInfo", JSON.stringify(this.remindInfo));
      localStorage.setItem("jobContent", this.jobContent);
      localStorage.setItem("goalContent", this.goalContent);
      this.$router.push({
        name: "ChooseMember",
        params: { memberList: this.memberList, leaderOrMember: "goalMember" },
      });
    },
    onSelect(currentValue) {
      this.deadline = currentValue;
      this.isShowDeadline = false;
      this.onBlur();
    },
    getPickedReplayTime(val) {
      this.remindInfo = val[0];
      this.isShowAlarmTime = val[1];
      this.isRemind = val[2];
      this.onBlur();
    },
    getAlarmTime() {
      if (!this.remindInfo.remindTime) {
        return "不提醒";
      } else {
        let arr = "";
        this.remindInfo.remindDays.forEach((element) => {
          if (element !== null) {
            arr += element.chinese + " ";
          }
        });
        if (arr === "") {
          return "不提醒";
        } else {
          return this.remindInfo.remindTime.substring(0, 5) + " " + arr;
        }
      }
    },
    getMemberList() {
      if (this.taskItem !== undefined) {
        let executors = this.taskItem.executors;
        let principal = this.taskItem.principal;
        if (executors.length !== 0) {
          executors.forEach((element) => {
            this.memberList.push(element.userId);
          });
        }
        if (principal.length !== 0) {
          principal.forEach((element) => {
            this.memberList.push(element.userId);
          });
        }
      } else {
        this.memberList = [];
      }
    },
    // 这个是构造最新添加的那个分工内容
    getTemp() {
      if (!this.jobContent) {
        this.nowTemp = undefined;
        return;
      }
      this.nowTemp = {
        jobContent: this.jobContent,
        userList:
          this.goalMemberChoosedItem === "" ? [] : this.goalMemberChoosedItem,
      };
      return this.nowTemp;
    },
    addJob() {
      this.isAdd = true;
      this.addGoal();
      //任务分工清零
      this.jobContent = "";
      this.goalMemberChoosedItem = [];
      localStorage.setItem("jobContent", "");
      localStorage.setItem("goalMemberChoosedItem", "");
    },
    judgeData() {
      if (this.isOnBlur) {
        if (this.goalContent.trim() === "") {
          this.alertInfo = "请填写【阶段目标简介】";
          return false;
        } else if (!this.deadline) {
          this.alertInfo = "请选择【截止日期】";
          return false;
        } else if (!this.remindInfo) {
          this.alertInfo = "请选择【提醒时间】";
          return false;
        } else {
          return true;
        }
      } else if (!this.goalMemberChoosedItem) {
        this.showAlert("请选择【负责人】");
        return false;
      }
      return true;
    },
    async addGoal() {
      if (this.isAdd && !this.judgeData()) {
        return;
      }
      let goalData = this.getGoalData();
      if (this.goalId === "" || this.goalId === undefined) {
        const result = await task.postAddGoal(goalData);
        if (result.code === 1) {
          if (this.isOnBlur) {
            this.alertInfo = "已自动保存成功";
          }
          if (!this.isOnBlur && this.nowTemp !== undefined && this.isAdd) {
            this.placements.push(this.nowTemp);
          }
          this.goalId = result.data;
          // 这个是解决，第一次创建阶段目标成功后，紧接着创建分工
          localStorage.setItem("goalId", this.goalId);
          this.showAlert("目标保存成功");
          setTimeout(this.closeTip, 1000);
        } else if (result.code === 0) {
          if (this.isOnBlur) {
            this.alertInfo = "自动保存失败，请稍后重试";
          }
          this.showAlert(result.message);
        }
      } else {
        // 修改postModifyGoal
        const result = await task.postModifyGoal(goalData);
        if (result.code === 1) {
          if (this.isOnBlur) {
            this.alertInfo = "已自动保存成功";
          }
          if (!this.isOnBlur && this.nowTemp !== undefined && this.isAdd) {
            this.placements.push(this.nowTemp);
          }
          this.showAlert("【目标分工】修改成功");
          setTimeout(this.closeTip, 1000);
        } else if (result.code === 0) {
          if (this.isOnBlur) {
            this.alertInfo = "自动保存失败，请稍后重试";
          }
          this.showAlert("【目标分工】修改失败，请重试！");
        }
      }
      localStorage.setItem("placements", JSON.stringify(this.placements));
    },
    getGoalData() {
      if (this.placements == null) {
        this.placements = [];
      }
      let placementsTemp = [];
      this.placements.forEach((element) => {
        placementsTemp.push(this.tempToNeed(element));
      });
      // 把最新的加到placementsTemp，此时页面显示placements还没添加，需要创建成功后
      if (!this.isOnBlur) {
        if (this.getTemp() !== undefined) {
          placementsTemp.push(this.tempToNeed(this.nowTemp));
        }
      }
      console.log("placementsTemp");
      console.log(placementsTemp);
      if (this.flagOfGoal) {
        this.goalId = this.goal.goalId;
      }
      let temp = {
        deadline: this.deadline,
        time: this.remindInfo.remindTime,
        weeks: time.weekToEnglish(this.remindInfo.remindDays),
        detail: {
          goalContent: this.goalContent.trim(),
          isFinish: false,
          placements: placementsTemp,
        },
        projectId: this.taskItem.projectId,
        goalId: +this.goalId,
      };
      return temp;
    },
    async deleteGoal() {
      const result = await task.getDeleteGoal(this.goal.goalId);
      if (result.code == 1) {
        this.showAlert("删除成功！");
        this.$router.go(-1);
      } else {
        this.showAlert("删除失败！");
      }
    },
    // TODO:这里的修改还需要进一步的考虑
    editFun(item, index) {
      this.jobContent = item.jobContent;
      this.placements.splice(index, 1);
      this.deleteFun(index);
    },
    deleteFun(index) {
      this.isAdd = false;
      this.placements.splice(index, 1);
      this.addGoal();
    },
    // 将当前页面显示的转为接口需要的
    tempToNeed(temp) {
      if (temp === null) {
        return null;
      }
      let userListTemp = [];
      if (!!temp.userList) {
        temp.userList.forEach((element) => {
          userListTemp.push(element.userId);
        });
      }
      return {
        jobContent: temp.jobContent,
        userList: userListTemp,
      };
    },
  },
};
</script>

<style >
#app {
  background-color: white;
}
</style>
<style lang="less" scoped>
.picker {
  display: inline-block;
  background-color: #dce0e2;
  border-radius: 20px;
  margin: 5px;
  padding: 3px 5px;
  margin-left: 15px;
  span {
    font-size: 12px;
  }
}
.taskWrap {
  .timeInfo {
    .picker;
  }
  .alertInfo {
    color: gray;
  }
  .goalsListWrap {
    padding: 0;
    .goalsList {
      display: flex;
      padding: 5px 20px;
      line-height: 25px;
      border-bottom: 1px solid rgb(237, 237, 237);
      display: flex;
      justify-content: space-between;
      div {
        display: flex;
        .circle {
          line-height: 50px;
          margin-right: 10px;
          font-size: 20px;
          color: #dce0e2;
        }
        .check {
          color: gray;
        }
        .jobs {
          display: flex;
          flex-direction: column;

          .jobTitle {
            font-size: 16px;
            font-weight: bolder;
          }
          .jobMember {
            font-size: 12px;
            color: gray;
            display: flex;
            flex-direction: row;
            span {
              font-size: 12px;
              color: gray;
            }
          }
        }
      }
      .edit {
        font-size: 25px;
        i {
          line-height: 50px;
          padding: 0 10px;
        }
      }
    }
  }
  .addJob {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: rgb(237, 237, 237);
    .addWrap {
      .addButton {
        float: right;
        background-color: green;
        border-radius: 20px;
        padding: 5px 8px;
        margin-left: 5px;
        font-size: 12px;
        color: white;
        line-height: 50px;
      }
      .jobContent {
        min-width: 70%;
        background-color: white;
        border-radius: 20px;
        margin: 5px;
      }
    }
    .picker {
      .picker;
      .choosedUser {
        img {
          width: 20px;
          height: 20px;
          vertical-align: middle;
          border-radius: 20px;
        }
      }
    }
  }
}
</style>